<template>
  <continer :isNoTabs="true" class="agentMonitoring" :showPage="showPage">
    <template slot="search">
      <QuickSearch :advForm="quickSearchForm" @QuickSearch="handleSearchFunc"></QuickSearch>
    </template>
    <template slot="oprate">
      <el-button size="mini" @click="reset">重置</el-button>
      <el-button type="primary" size="mini" @click="handleSearchFunc">查询</el-button>
    </template>
    <template slot="content">
      <!-- 表格 -->
      <configTable
        ref="table"
        v-if="showTable"
        :headers="tableHeaders"
        :data="tableData"
        :batchs="batchs"
        :pagingData="pagingData"
        @pageChange="handleCurrentChange"
        @pageSizeChange="handleSizeChange"
        @checkHeadersChange="checkHeadersChange"
        :selection="batchs.length > 0"
        @batchClick="batchClick"
        :headersConfig="false"
      >
        <template slot="column">
          <template v-for="(item, index) in checkHeaders">
            <u-table-column
              v-if="item.show && item.prop !== 'oprate'"
              :key="index"
              :label="item.label"
              :prop="item.prop"
              :sortable="item.sortable"
              :min-width="item.width || 80"
            >
            <template slot-scope="scope">
              <span v-if="item.prop.includes('count')">{{ scope.row[item.prop] || 0 }}</span>
              <span v-else-if="item.prop.includes('time')">{{ scope.row[item.prop] || '00:00:00' }}</span>
              <span v-else>{{ scope.row[item.prop] }}</span>
            </template>
            </u-table-column>
            <u-table-column
              v-if="item.show && item.prop === 'oprate'"
              :key="index"
              :label="item.label"
              :resizable="false"
              :width="80"
              fixed="right"
            >
              <template slot-scope="scope">
                <span class="oprate-span" @click="openPage(scope.row)">查看详情</span>
              </template>
            </u-table-column>
          </template>
        </template>
      </configTable>
    </template>
    <template slot="page" :isNoTabs="true">
      <Detail :detailId="detailId" :detailTime="detailTime" @closePage="closePage"></Detail>
    </template>
  </continer>
</template>

<script lang="ts">
/**
 * 在线座席日志
 */
import { Component, Vue } from 'vue-property-decorator'
import QuickSearch from '@/components/globalTool/search/index.vue'
import continer from '@/common/views/configCommon/ui-modules/handle-wrapper.vue'
import configTable from '@/components/globalTool/resizeTable/index.vue'
import { commonAction, isHasFuncOrMenus } from '@/utils/common'
import { CommonModule } from '@/store/modules/common'
import Detail from './components/detail.vue'
import { today, getTime, mixHeader, getAgentName, getAllStatusCount } from './components/index'
@Component({
  name: 'NoticeSetting',
  components: {
    QuickSearch,
    configTable,
    continer,
    Detail
  }
})
export default class NoticeSetting extends Vue {
  [x: string]: any
  private tableData: any = []
  private pagingData: any = { total: 0, limit: 10, page: 1 }
  private checkHeaders: [] = []
  private quickSearchForm: any = {}
  private showPage = false
  private detailId: string = ''
  private detailTime: any = []
  private showTable = false

  // 获取座席数组
  get AgentList () {
    return (CommonModule as any).publicCache.userList.map(v => ({ name: `${v.agentName} 【${v.agentNumber}】`, _id: v._id }))
  }

  private tableHeaders: object[] = []

  // 初始化搜索数据，表头数据
  private async initData () {
    this.quickSearchForm = {
      form: {
        userId: [],
        peerIds: [],
        createTime: today()
      },
      advSearchOptions: [
        { label: '座席', name: 'userId', inputType: 'select', clearable: true, selectData: this.AgentList, placeholder: '请选择', multiple: true },
        { label: '技能组', name: 'peerIds', inputType: 'select', selectData: CommonModule.publicCache.queueList, clearable: true, placeholder: '请选择', multiple: true },
        { label: '登录时间', name: 'createTime', inputType: 'dateTimeRange', clearable: false }
      ]
    }
    const header = await mixHeader()
    this.tableHeaders = [
      { label: '座席', prop: 'agentName', width: 150 },
      { label: '登录次数', prop: 'loginCount' },
      ...header.count,
      { label: '自定义状态次数', prop: 'statusCount', width: 120 },
      { label: '修改会话上限次数', prop: 'modifySessionUpperLimitCount', width: 120 },
      { label: '在线总时长', prop: 'onlineTimeLength', width: 100 },
      ...header.time,
      { label: '操作', prop: 'oprate', disenable: true }
    ]
    // 初始化表头之后在显示表格
    this.showTable = true
  }

  // 重置搜索数据
  private reset () {
    this.quickSearchForm.form = {
      userId: [],
      peerIds: [],
      createTime: today()
    }
    this.handleSearchFunc()
  }

  private async mounted () {
    await this.initData()
    this.getData()
  }

  // 获取数据
  private async getData () {
    if (!this.quickSearchForm.form.createTime) {
      this.quickSearchForm.form.createTime = today()
    }
    const diff = new Date(this.quickSearchForm.form.createTime[1]).getTime() - new Date(this.quickSearchForm.form.createTime[0]).getTime()
    if (diff > 365 * 24 * 3600 * 1000) {
      this.$message.error('搜索时间范围不能超过一年')
      return
    }
    const actionData: any = {
      limit: this.pagingData.limit,
      page: this.pagingData.page,
      ...this.quickSearchForm.form
    }
    const data: any = await commonAction({ url: '/im-center/action/userLog/imUserLog/allAgentList', method: 'POST', data: actionData })
    if (data.success) {
      // 对数据预处理，遍历数据添加表头对应属性值
      this.tableData = data.data.list.map(v => {
        const object = { ...v }
        object.agentName = getAgentName(v.agentNumber)
        object.onlineTimeLength = getTime(v.onlineTimeLength)
        const map = object.statusConfigInfo
        object.statusCount = getAllStatusCount(map)
        for (const i in map) {
          object[i + 'count'] = map[i].count || 0
          object[i + 'time'] = getTime(map[i].timeLength)
        }
        return object
      })
      this.pagingData.total = data.data.count
    }
  }

  // 搜索
  private handleSearchFunc () {
    this.pagingData.page = 1
    if (!this.quickSearchForm.form.createTime) {
      this.quickSearchForm.form.createTime = this.today
    }
    this.getData()
  }

  // 查看详情
  private openPage (row: any) {
    this.detailId = row._id
    this.detailTime = this.quickSearchForm.form.createTime
    this.showPage = true
  }

  private closePage () {
    this.showPage = false
  }

  private checkHeadersChange (checkList) {
    this.$set(this, 'checkHeaders', checkList)
  }

  private handleSizeChange (size: number) {
    this.pagingData.limit = size
    this.handleSearchFunc()
  }

  private handleCurrentChange (page: number) {
    this.pagingData.page = page
    this.getData()
  }

  private batchs: any = []

  private created () {
    if (isHasFuncOrMenus('im_monitor_log_list_export', this.$store.state.common.session.user, false)) {
      this.batchs.push({
        name: '导出列表',
        action: 'exportList'
      })
    }
    if (isHasFuncOrMenus('im_monitor_log_detail_export', this.$store.state.common.session.user, false)) {
      this.batchs.push({
        name: '导出详情',
        action: 'exportDetail'
      })
    }
  }

  private batchClick (action: string, selectList: any) {
    const data: any = {
      count: this.pagingData.total
    }
    if (selectList !== true) {
      data.count = selectList.length
      data.ids = selectList
    }
    switch (action) {
      case 'exportList':
        this.exportList(data)
        break
      case 'exportDetail':
        this.exportDetail(data)
        break
    }
  }

  private async exportList (ids) {
    const actionData: any = {
      condition: {
        ...this.quickSearchForm.form
      },
      comment: '在线坐席日志列表导出',
      ...ids,
      type: 'imMonitorLog'
    }
    const data: any = await commonAction({ url: '/im-center/action/userLog/imUserLog/exportAgentLog', method: 'POST', data: actionData })
    if (data.success) {
      const h = this.$createElement
      this.$message({
        message: h('div', { style: 'color:#2ed47a' }, [
          h('span', {}, `导出任务${data.data.taskId || ''}进入排队，请前往`),
          h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
          h('span', {}, '查看')
        ]),
        type: 'success',
        duration: 5000
      })
    }
  }

  private async exportDetail (ids) {
    const actionData: any = {
      condition: {
        ...this.quickSearchForm.form
      },
      comment: '在线坐席日志详情导出',
      ...ids,
      type: 'imMonitorDetailLog'
    }
    const data: any = await commonAction({ url: '/im-center/action/userLog/imUserLog/exportAgentLog', method: 'POST', data: actionData })
    if (data.success) {
      const h = this.$createElement
      this.$message({
        message: h('div', { style: 'color:#2ed47a' }, [
          h('span', {}, `导出任务${data.data.taskId || ''}进入排队，请前往`),
          h('a', { on: { click: this.jumpToTransmissionCenter }, style: 'cursor:pointer,color:#008cee' }, '传输中心'),
          h('span', {}, '查看')
        ]),
        type: 'success',
        duration: 5000
      })
    }
  }

  private jumpToTransmissionCenter () {
    this.$router.push('/transmission_center/index/tx_export_task')
  }
}
</script>
<style lang="stylus" scoped>
.agentMonitoring
  /deep/ .el-tag
            max-width: 100px
.oprate-span
  cursor pointer
  color $c-main
  margin 0 4px
</style>
